//
//  MWFilterMenuView.m
//  XiRan-iOS
//
//  Created by Richfit on 2019/10/29.
//  Copyright © 2019 Wood. All rights reserved.
//

#import "MWFilterMenuView.h"
#import "MWFilterMenuCell.h"
#import "MWFilterMenuHeaderView.h"

#import "XiRan_iOS-Swift.h"
#import "CSFilterMenuSubCategorysContentView.h"

@interface MWFilterMenuView () <UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, CellFooterCollectionViewDelegate>

@property(nonatomic, strong) UIView *backgroundView;

@property(nonatomic, strong) UIView *contentView;
@property(nonatomic, strong) CellFooterCollectionView *collectionView;
@property (nonatomic, strong) CSCellFooterLayout *flowlayout;
@property(nonatomic, strong) UIView *bottomView;
@property(nonatomic, strong) UIButton *resetBtn;
@property(nonatomic, strong) UIButton *ensureBtn;

@property(nonatomic, strong) NSMutableArray *filterArray;

@property (nonatomic, strong) UIView *heardView;

@property (nonatomic, strong) NSMutableDictionary *selectSubAttributes;

@property (nonatomic, strong) NSString *customSearchContentView;
@property (nonatomic, strong) UITextField *customSearchView;


@end

@implementation MWFilterMenuView

- (instancetype)initWithFrame:(CGRect)frame {
    if (!(self =[super initWithFrame:[[UIScreen mainScreen] bounds]])) {
        return nil;
    }
    
    self.selectSubAttributes = [NSMutableDictionary dictionary];
    [self setupPageSubviews];
    
    return self;
}

- (void)tapGesture:(UIGestureRecognizer *)sender {
    for (MWFilterModel *model in self.filterArray) {
        for (MWAttribute *attr in model.attr_list) {
            if (attr.isSelected) {
                if (!attr.isEnsure) {
                    attr.isSelected = NO;
                    attr.isEnsure = NO;
                }
            }
        }
    }
    
    [self dismiss];
}

- (void)resetAction:(UIButton *)sender {
    for (MWFilterModel *model in self.filterArray) {
        for (MWAttribute *attr in model.attr_list) {
            attr.isSelected = NO;
            attr.isEnsure = NO;
            [attr.attr_list setValue:@NO forKey:@"isSelected"];
            [attr.attr_list setValue:@NO forKey:@"isEnsure"];
            if(attr.mid < 0) {
                attr.customValue = @"";
            }
        }
    }
    [self.selectSubAttributes removeAllObjects];
    [self.flowlayout resetCellFooters];
    [_collectionView reloadData];
    
    if (self.resetBlock) {
        self.resetBlock();
    }
    [self dismiss];
}

- (void)ensureAction:(UIButton *)sender {
    for (MWFilterModel *model in self.filterArray) {
        for (MWAttribute *attr in model.attr_list) {
            if (attr.isSelected) {
                attr.isEnsure = YES;
            }
            if(model.child) {
                for(MWSubattribute *subAttr in attr.attr_list) {
                    subAttr.isEnsure = subAttr.isSelected;
                }
            }
        }
    }
    
    if (self.selectBlock) {
        self.selectBlock();
    }
    [self dismiss];
}

- (void) setContentArray:(NSArray *)array {
    [self.filterArray removeAllObjects];
    [self.filterArray addObjectsFromArray:array];
    [_collectionView reloadData];
}

- (void)show {
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    [window addSubview:self];
    
    _backgroundView.alpha = 0.0;
    _contentView.frame = CGRectMake(kScreenWidth, 0, kScreenWidth - 40, kScreenHeight);
    MWWeakSelf
    [UIView animateWithDuration:0.3 animations:^{
        weakSelf.backgroundView.alpha = 0.6;
        weakSelf.contentView.frame = CGRectMake(40, 0, kScreenWidth - 40, kScreenHeight);
        
    } completion:^(BOOL finished) {
        
    }];
}

- (void)dismiss {
    MWWeakSelf
    [UIView animateWithDuration:0.3 animations:^{
        weakSelf.backgroundView.alpha = 0.0;
        weakSelf.contentView.frame = CGRectMake(kScreenWidth, 0, kScreenWidth - 40, kScreenHeight);
    
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
        
    }];
}

#pragma mark - UICollectionViewDataSource && UICollectionViewDelegate
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return self.filterArray.count;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    MWFilterModel *model = self.filterArray[section];
    return model.attr_list.count;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    if (kind == UICollectionElementKindSectionHeader) {
        MWFilterMenuHeaderView *headerView = nil;
        headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"MWFilterMenuHeaderView" forIndexPath:indexPath];
        MWFilterModel *model = self.filterArray[indexPath.section];
#if DEBUG
        if(model.attr_name.length == 0) {
            headerView.title = @"缺少翻译";
        } else {
            headerView.title = model.attr_name;
        }
#else
        headerView.title = model.attr_name;
#endif
        return headerView;
    }
    CSFilterMenuSubCategorysContentView *contentView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"footer" forIndexPath:indexPath];
    contentView.subattributes = [self.selectSubAttributes valueForKey:[NSString stringWithFormat:@"%@", @(indexPath.section)]];
    return contentView;
}

- (void)footerWillReuseAtIndexPath:(NSIndexPath *)indexPath reuseView:(UICollectionReusableView *)reuseView forCollectionView:(UICollectionView *)forCollectionView
{
    if(![reuseView isKindOfClass:[CSFilterMenuSubCategorysContentView class]]) {
        return;
    }
    CSFilterMenuSubCategorysContentView *contentView = (id)reuseView;
    contentView.subattributes = [self.selectSubAttributes valueForKey:[NSString stringWithFormat:@"%@", @(indexPath.section)]];
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *identifier = @"MWFilterMenuCell";
    MWFilterMenuCell *filterCell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
   
    MWFilterModel *model = self.filterArray[indexPath.section];
    MWAttribute *attribute = model.attr_list[indexPath.row];
    
//    filterCell.block = ^{
//        if ( attribute.isSelected) {
//             attribute.isSelected = NO;
//        } else {
//             attribute.isSelected = YES;
//        }
//        [weakSelf.collectionView reloadData];
//    };
    filterCell.indexPath = indexPath;
    MWWeakSelf
    filterCell.checkWithIndexPathBlock = ^(NSIndexPath *indexPath) {
        if ( attribute.isSelected) {
            attribute.isSelected = NO;
        } else {
            attribute.isSelected = YES;
        }
        
        if(attribute.mid >= 0) {
            if(model.child && attribute.isSelected && attribute.attr_list.count > 0) {
                [self.selectSubAttributes setValue:attribute.attr_list forKey:[NSString stringWithFormat:@"%@", @(indexPath.section)]];
                [weakSelf.flowlayout setFooterForCellAtIndexPath:indexPath];
            } else {
                [attribute.attr_list setValue:@NO forKey:@"isSelected"];
                [weakSelf.selectSubAttributes removeObjectForKey:[NSString stringWithFormat:@"%@", @(indexPath.section)]];
                [weakSelf.flowlayout setFooterForCellInSection:indexPath.section];
            }
        } else {
            //自定义内容
            if(attribute.isSelected) {
                [self inputCustomValueWithModel:attribute];
            }
        }
        weakSelf.collectionView.userInteractionEnabled = NO;
        [weakSelf.collectionView reloadData];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [weakSelf.collectionView reloadData];
            weakSelf.collectionView.userInteractionEnabled = YES;
        });
    };
    
#if DEBUG
    if(attribute.showAttr_value.length == 0) {
        filterCell.title = @"缺少翻译";
    } else {
        filterCell.title = attribute.showAttr_value;
    }
#else
    filterCell.title = attribute.showAttr_value;
#endif
    filterCell.isSelected = attribute.isSelected;
    
    return filterCell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
}

#pragma mark - UICollectionViewDelegateFlowLayout
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return 12;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return 10;
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(0, 20, 0, 20);
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    return CGSizeMake(kScreenWidth, 50);
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section {
    NSArray *selectSubAttributes = [self.selectSubAttributes valueForKey:[NSString stringWithFormat:@"%@", @(section)]];
    if(selectSubAttributes.count > 0) {
        CGFloat lineNums = ceil(selectSubAttributes.count / 2.0);
        return CGSizeMake(kScreenWidth, 40 * lineNums + (lineNums - 1) * 12 + 10);
    }
    return CGSizeZero;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return CGSizeMake((kScreenWidth - 40 - 50) / 2, 40);
}

- (NSMutableArray *)filterArray {
    if (!_filterArray) {
        _filterArray = [[NSMutableArray alloc] init];
    }
    return _filterArray;
}

- (UIView *)heardView {
    if (_heardView == nil) {
        _heardView = [[UICollectionReusableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth - 40, 50)];
        _heardView.backgroundColor = [UIColor clearColor];
        
        UIButton *backButton = [[UIButton alloc] init];
        [backButton setImage:[UIImage imageNamed:@"ic_arrow_left"] forState:UIControlStateNormal];
        [backButton addTarget:self action:@selector(backButtonClick) forControlEvents:UIControlEventTouchUpInside];
        [_heardView addSubview:backButton];
        
        UILabel *titleLabel = [[UILabel alloc] init];
        titleLabel.font = [UIFont boldSystemFontOfSize:20];
        titleLabel.textColor = MWHexColor(@"#333333");
        titleLabel.textAlignment = NSTextAlignmentCenter;
        titleLabel.text = [[MWConfigManager manager] objectForKey:@"filter_by" defaultValue:@"筛选条件"];
        [_heardView addSubview:titleLabel];
        
        [backButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(_heardView);
            make.top.equalTo(_heardView);
            make.width.equalTo(@40);
            make.height.equalTo(@(_heardView.frame.size.height));
        }];
        
        [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(backButton.mas_right);
            make.top.right.equalTo(_heardView);
            make.height.equalTo(@(_heardView.frame.size.height));
        }];
        
    }
    return _heardView;
}
#pragma mark - 返回按钮的监听事件
- (void)backButtonClick {
    [self dismiss];
}

- (void)setupPageSubviews {
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGesture:)];
    _backgroundView = [[UIView alloc] initWithFrame:self.frame];
    _backgroundView.backgroundColor = [UIColor blackColor];
    _backgroundView.alpha = 0.0;
    [_backgroundView addGestureRecognizer:tapGesture];
    [self addSubview:_backgroundView];
    
    
    _contentView = [[UIView alloc] initWithFrame:CGRectZero];
    _contentView.backgroundColor = [UIColor whiteColor];
    [self addSubview:_contentView];
    
    CSCellFooterLayout *layout = [[CSCellFooterLayout alloc] init];
    layout.flowlayoutDelegate = self;
    self.flowlayout = layout;
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    _collectionView = [[CellFooterCollectionView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth - 40, kScreenHeight - 80) collectionViewLayout:layout];
    _collectionView.footerDelegate = self;
    _collectionView.backgroundColor = [UIColor whiteColor];
    _collectionView.dataSource = self;
    _collectionView.delegate = self;
    [_collectionView registerClass:[MWFilterMenuCell class] forCellWithReuseIdentifier:@"MWFilterMenuCell"];
    [_collectionView registerClass:[MWFilterMenuHeaderView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"MWFilterMenuHeaderView"];
    [_collectionView registerClass:[CSFilterMenuSubCategorysContentView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"footer"];
    _collectionView.cellClass = [CSFilterMenuSubCategorysContentView class];
    [_contentView addSubview:_collectionView];
    
    _collectionView.contentInset = UIEdgeInsetsMake(50, 0, 0, 0);
    self.heardView.frame = CGRectMake(0, -50, kScreenWidth - 40, 50);
    [_collectionView addSubview:self.heardView];
    [_collectionView setContentOffset:CGPointMake(0, -50)];

    
    _bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, kScreenHeight - 80, kScreenWidth, 80)];
    [_contentView addSubview:_bottomView];
    
    _resetBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _resetBtn.frame = CGRectMake((kScreenWidth - 40) / 2 - 100, 24, 84, 32);
    _resetBtn.layer.cornerRadius = 5;
    _resetBtn.layer.masksToBounds = YES;
    _resetBtn.layer.borderWidth = 1;
    _resetBtn.layer.borderColor = MWHexColor(@"#E7E7E7").CGColor;
    _resetBtn.titleLabel.font = MWFont(15);
    [_resetBtn setTitle:[[MWConfigManager manager] objectForKey:@"resetting" defaultValue:@"重置"] forState:UIControlStateNormal];
    [_resetBtn setTitleColor:MWHexColor(@"#333333") forState:UIControlStateNormal];
    [_resetBtn setBackgroundImage:[UIImage imageWithColor:[UIColor whiteColor]] forState:UIControlStateNormal];
    [_resetBtn addTarget:self action:@selector(resetAction:) forControlEvents:UIControlEventTouchUpInside];
    [_bottomView addSubview:_resetBtn];
    
    _ensureBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _ensureBtn.frame = CGRectMake((kScreenWidth - 40) / 2 + 16, 24, 84, 32);
    _ensureBtn.layer.cornerRadius = 5;
    _ensureBtn.layer.masksToBounds = YES;
    _ensureBtn.titleLabel.font = MWFont(15);
    [_ensureBtn setTitle:[[MWConfigManager manager] objectForKey:@"define" defaultValue:@"确定"] forState:UIControlStateNormal];
    [_ensureBtn setTitleColor:MWHexColor(@"#FFFFFF") forState:UIControlStateNormal];
    [_ensureBtn setBackgroundImage:[UIImage imageWithColor:MWHexColor(@"#FD9F2B")] forState:UIControlStateNormal];
    [_ensureBtn addTarget:self action:@selector(ensureAction:) forControlEvents:UIControlEventTouchUpInside];
    [_bottomView addSubview:_ensureBtn];
}

- (void)inputCustomValueWithModel:(MWAttribute *)model
{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"请输入自定义值" preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
        
    }];
    UIAlertAction *saveAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        model.customValue = alert.textFields.firstObject.text;
        [self.collectionView reloadData];
    }];
    [alert addAction:cancelAction];
    [alert addAction:saveAction];
    
    [alert addTextFieldWithConfigurationHandler:^(UITextField *textField) {
        textField.textColor = [UIColor blackColor];
        textField.text = model.customValue;
        textField.placeholder = @"自定义条件";
    }];
    [[self viewControllerFromSelf] presentViewController:alert animated:YES completion:^{
        
    }];
}

- (UIViewController *)viewControllerFromSelf
{
    return self.window.rootViewController;
}

@end
